/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.PageDao;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Page;

/**
 * This controller handles all the page views; With the parameter it will check
 * if the page exists and will return the content of it.
 *
 * @author Sander
 */
public class PageController extends HttpServlet {

    /**
     * This doGet checks wether the page exists or not and put the returned
     * information in an attribute.
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher dispatcher;
        HibernateUtil hu = new HibernateUtil();
        PageDao dao = new PageDao(hu.openSession());

        if (request.getParameter("p") != null) {
            // Put the first letter of the title to capital
            String p = request.getParameter("p").substring(0, 1).toUpperCase() + request.getParameter("p").substring(1);

            List<Page> page = dao.findPageByTitle(p);

            if (page.isEmpty()) { // If the page doesn't exists
                response.sendRedirect("Index");
                return;
            }

            request.setAttribute("page", page);
            request.setAttribute("title", p.replace("_", " "));

            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Page", p.replace("_", " "))
            };
            request.setAttribute("breadcrumbs", breadcrumbs);

            hu.close();
            
            dispatcher = request.getRequestDispatcher("jsp/page.jsp");
            dispatcher.forward(request, response);
        }
    }
}
